package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrEnum;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;
import java.util.Optional;
public class ConnectResponseInfo extends AxdrType {
    private byte[] dataCode = null;
    private AxdrEnum connectResult = null;
    private Optional<SecurityData> securityData = Optional.empty();

    public ConnectResponseInfo() {
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(AxdrEnum connectResult, SecurityData securityData) {
        this.connectResult = connectResult;
        this.securityData = Optional.of(securityData);
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.connectResult = new AxdrEnum();
        this.connectResult.setConst();
        codeLength += this.connectResult.decode(input);
        this.securityData = Optional.of(new SecurityData());
        codeLength += this.securityData.get().decode(input);
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength = 0;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if (this.connectResult != null && this.securityData.isPresent()) {
                codeLength += this.securityData.get().encode(output);
                codeLength += this.connectResult.encode(output);
            } else {
                throw new Exception("securityData or connectResult is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.toByteArray();
    }

    @Override
    public String toString() {
        if (this.securityData.isPresent() && this.connectResult != null) {
            return "sequence: {" + "connectResult: " + this.connectResult + ", securityData: " + this.securityData.get() + "}";
        } else {
            return "securityData || connectResult is null";
        }
    }
}



